package cn.edu.lzu.unitweb.controller;

import cn.edu.lzu.common.assist.DataPage;
import cn.edu.lzu.common.assist.ResponseResult;
import cn.edu.lzu.entity.Examiner;
import cn.edu.lzu.entity.ProfessionalTitle;
import cn.edu.lzu.entity.Role;
import cn.edu.lzu.entity.Unit;
import cn.edu.lzu.service.ExaminerService;
import cn.edu.lzu.service.ProfessionalTitleService;
import cn.edu.lzu.service.RoleService;
import cn.edu.lzu.service.UnitService;
import cn.edu.lzu.unitweb.config.ExaminerSessionDao;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.servlet.ShiroHttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.*;


@Controller
public class ExaminerController {
    @Resource
    private ExaminerService examinerService;
    @Resource
    private UnitService unitService;
    @Resource
    private ExaminerSessionDao examinerSessionDao;
    @Resource
    private ProfessionalTitleService professionalTitleService;
    @Resource
    private RoleService roleService;

    /**
     * @Author: 张琦[QQ:3098086691]
     * @Description: TODO 检查‘医护人员’登录；如果该账号在其它设备登录，则强制在其它设备退出(遍历所有活跃的session， 与当前的sessionId对比，当sessionId不同但是session中的principals相同，就销毁该session
     * @Date: 2019/11/29 12:48
     * @Param: [username, password]
     * @Return: cn.edu.lzu.common.assist.ResponseResult
     **/
    @ResponseBody
    @RequestMapping("/checkExaminerLogin")
    public ResponseResult checkExaminerLogin(long username, String password, HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username + "", password);
        ResponseResult responseResult = new ResponseResult();
        try {
            subject.login(token);
            responseResult.setCode(1);
            responseResult.setMsg("登录成功");
            //更新‘上次登录时间’
            examinerService.updateExaminerLastLoginTime(username);
            Unit unit = unitService.selectUnitById(Long.valueOf((username + "").substring(0, 6)));
            subject.getSession().setAttribute("unit", unit);
            subject.getSession().setAttribute("examiner", ((PrincipalCollection)subject.getSession().getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)).getPrimaryPrincipal());

            Collection<Object> attributes=subject.getSession().getAttributeKeys();
            for(Object object:attributes){
                System.out.println(object+"："+subject.getSession().getAttribute(object));
            }

            //强制登录在其它设备的账号下线
            //本设备的sessionId：
            Serializable sessionId = subject.getSession().getId();
            //所有的session；
            Collection<Session> sessions = examinerSessionDao.getActiveSessions();
            for (Session session : sessions) {
                //session保存的examiner；
                PrincipalCollection principalCollection = (PrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
                //如果该session不是当前的session并且它保存的examiner的id==当前session保存的examiner的id，则将该session销毁；
                if (session.getId() != sessionId) {
                    if (((Examiner) (principalCollection.getPrimaryPrincipal())).getExaminerId() == username) {
                        session.stop();
                    }
                }
            }
        } catch (IncorrectCredentialsException e) {
            System.out.println(e);
            responseResult.setCode(0);
            responseResult.setMsg("登录失败:密码或着账号不正确");

        } catch (UnknownAccountException e) {
            System.out.println(e);
            responseResult.setCode(0);
            responseResult.setMsg("登录失败:密码或着账号不正确");

        } catch (LockedAccountException e) {
            System.out.println(e.getLocalizedMessage());
            responseResult.setCode(0);
            if((e.getLocalizedMessage()).equals("您所在的单位已被停用！")){
                responseResult.setMsg("登录失败:您所在的单位已被停用！");
            }else if((e.getLocalizedMessage()).equals("您的账号已被停用!")){
                responseResult.setMsg("登录失败:您的账号已被停用!");
            }


        } catch (AuthenticationException e) {
            System.out.println(e);
            responseResult.setCode(0);
            responseResult.setMsg("登录失败:密码或着账号不正确");
        } catch (Exception e) {
            System.out.println(e);
            responseResult.setMsg("登录失败:密码或着账号不正确");
            responseResult.setCode(0);
        } finally {
            return responseResult;
        }
    }

    /**
     * @Author: 张琦[QQ:3098086691]
     * @Description: TODO 销毁session，退出登录
     * @Date: 2019/11/30 14:21
     * @Param: []
     * @Return: java.lang.String
     **/
    @RequestMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.logout();
        } catch (Exception e) {
            System.out.println(e);
        }
        return "login.html";
    }

    /**
     * @Author: 张琦[QQ:3098086691]
     * @Description: TODO 根据当前页码currentPageNum和页大小pageSize获取下一页的数据
     * @Date: 2019/12/2 11:03
     * @Param: [currentPageNum, pageSize]
     * @Return: cn.edu.lzu.common.assist.DataPage
     **/
    @ResponseBody
    @RequestMapping("/getExaminerList")
    public DataPage getExaminerList(int currentPageNum, int pageSize) {
        System.out.println("currentPageNum:" + currentPageNum + "\t pageSize:" + pageSize);
        //获取单位id：examinerId的前6位
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        PrincipalCollection principalCollection = (PrincipalCollection) (session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY));
        Examiner examiner = (Examiner) principalCollection.getPrimaryPrincipal();
        //单位编号是员工编号的前6位
        long unitId = Long.valueOf((examiner.getUnitId() + "").substring(0, 6));
        //获取一页数据
        DataPage examinerPage = examinerService.selectExaminerPage(currentPageNum, pageSize, unitId);
        return examinerPage;
    }

    /**
     * @Author: 张琦[QQ:3098086691]
     * @Description: TODO 更新账号启用|禁用状态
     * @Date: 2019/12/2 11:34
     * @Param: [examinerId, status]
     * @Return: cn.edu.lzu.common.assist.ResponseResult
     **/
    @ResponseBody
    @RequestMapping("/updateExaminerStatus")
    public ResponseResult updateExaminerStatus(long examinerId, boolean status) {
        ResponseResult responseResult = examinerService.updateExaminerStatus(examinerId, status);
        return responseResult;
    }

    /**
     * @Author: 张琦[QQ:3098086691]
     * @Description: TODO 获取所有的专业类型列表
     * @Date: 2019/12/2 21:18
     * @Param: []
     * @Return: java.util.List<cn.edu.lzu.entity.ProfessionalTitle>
     **/
    @ResponseBody
    @RequestMapping("/getAllProfessionalTypeList")
    public List<ProfessionalTitle> getProfessionalTypeList() {
        List<ProfessionalTitle> professionalTitleList = professionalTitleService.selectAllProfessionalTypes();
        return professionalTitleList;
    }

    /**
     * @Author: 张琦[QQ:3098086691]
     * @Description: TODO 获取‘职称’相关信息列表
     * @Date: 2019/12/3 15:24
     * @Param: [professionalType]
     * @Return: java.util.List<cn.edu.lzu.entity.ProfessionalTitle>
     **/
    @ResponseBody
    @RequestMapping("getProfessionalTitleListByType")
    public List<ProfessionalTitle> getProfessionalTitleListByType(String professionalType) {
        List<ProfessionalTitle> professionalTitleList = professionalTitleService.selectProfessionalTitlesByType(professionalType);
        return professionalTitleList;
    }

    /**
     * @Author: 张琦[QQ:3098086691]
     * @Description: TODO 注册一位新员工账号
     * @Date: 2019/12/3 16:56
     * @Param: [examiner]
     * @Return: cn.edu.lzu.common.assist.ResponseResult
     **/
    @ResponseBody
    @RequestMapping("/registeExaminer")
    public ResponseResult registeExaminer(Examiner examiner) {
        System.out.println("examiner:" + examiner);
        Session session = SecurityUtils.getSubject().getSession();
        //执行添加操作者的信息。
        Examiner operator = (Examiner) ((PrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)).getPrimaryPrincipal();
        examiner.setUnitId(operator.getUnitId());
        ResponseResult responseResult = examinerService.registeExaminer(examiner);
        return responseResult;
    }

    /**
     * @param null
     * @Author: 张琦[QQ:3098086691]
     * @Description: TODO 批量开启examiner账号
     * @Date: 2019/12/4 10:27
     * @Param:
     * @Return:
     **/
    @ResponseBody
    @RequestMapping("/batchEnabledExaminers")
    public ResponseResult batchEnabledExaminers(String examinerIds) {
        Session session = SecurityUtils.getSubject().getSession();
        //获取本单位的unitId
        long unitId = ((Examiner) ((PrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)).getPrimaryPrincipal()).getUnitId();
        ResponseResult responseResult = examinerService.batchEnabledExaminers(examinerIds);
        return responseResult;
    }

    /**
     * @Author: 张琦[QQ:3098086691]
     * @Description: TODO 批量禁用examiner账号
     * @Date: 2019/12/4 13:53
     * @Param: [examinerIds]
     * @Return: cn.edu.lzu.common.assist.ResponseResult
     **/
    @ResponseBody
    @RequestMapping("/batchDisenabledExaminers")
    public ResponseResult batchDisenabledExaminers(String examinerIds) {
        Session session = SecurityUtils.getSubject().getSession();
        //获取‘操作者’信息
        Examiner examiner = (Examiner) ((PrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)).getPrimaryPrincipal();
        ResponseResult responseResult = examinerService.batchDisenabledExaminers(examinerIds, examiner.getExaminerId());
        return responseResult;
    }

    /**
     * @Author: 张琦[QQ:3098086691]
     * @Description: TODO 批量删除账号
     * @Date: 2019/12/4 16:46
     * @Param: [examinerIds]
     * @Return: cn.edu.lzu.common.assist.ResponseResult
     **/
    @ResponseBody
    @RequestMapping("/batchDeleteExaminers")
    public ResponseResult batchDeleteExaminers(String examinerIds) {
        Session session = SecurityUtils.getSubject().getSession();
        //获取‘操作者’信息
        Examiner examiner = (Examiner) ((PrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)).getPrimaryPrincipal();
        ResponseResult responseResult = examinerService.batchDeleteExaminers(examinerIds, examiner.getExaminerId());
        return responseResult;
    }

    /**
     * @Author: 张琦[QQ:3098086691]
     * @Description: TODO 根据examinerId删除账号
     * @Date: 2019/12/4 17:07
     * @Param: [examinerId]
     * @Return: cn.edu.lzu.common.assist.ResponseResult
     **/
    @ResponseBody
    @RequestMapping("/deleteExaminerByExaminerId")
    public ResponseResult deleteExaminerById(long examinerId) {
        Session session = SecurityUtils.getSubject().getSession();
        //获取‘操作者’信息
        Examiner examiner = (Examiner) ((PrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)).getPrimaryPrincipal();
        ResponseResult responseResult = examinerService.deleteExaminerByExaminerId(examinerId, examiner.getExaminerId());
        return responseResult;
    }

    /**
     * @Author: 张琦[QQ:3098086691]
     * @Description: TODO 根据输入的examinerId进行模糊查询
     * @Date: 2019/12/4 21:54
     * @Param: [searchInput]
     * @Return: cn.edu.lzu.common.assist.DataPage
     **/
    @ResponseBody
    @RequestMapping("/fuzzySearchByExaminerId")
    public DataPage fuzzySearchByExaminerId(String searchInput, int pageSize) {
        System.out.println("searchInput: " + searchInput + "\t pageSize: " + pageSize);
        Session session = SecurityUtils.getSubject().getSession();
        //获取‘操作者’信息
        Examiner examiner = (Examiner) ((PrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)).getPrimaryPrincipal();
        DataPage examinerPage = new DataPage();
        examinerPage = examinerService.fuzzySearchByExaminerId(examiner.getUnitId(), searchInput, pageSize);
        return examinerPage;
    }

    /**
     * @Author: 张琦[QQ:3098086691]
     * @Description: TODO 修改密码
     * @Date: 2019/12/5 21:52
     * @Param: [originalPwd, newPwd, confirmPwd]
     * @Return: cn.edu.lzu.common.assist.ResponseResult
     **/
    @ResponseBody
    @RequestMapping("/updateSelfPassword")
    public ResponseResult updateSelfPwd(String originalPwd, String newPwd, String confirmPwd) {
        Session session = SecurityUtils.getSubject().getSession();
        //获取‘操作者’信息
        Examiner examiner = (Examiner) ((PrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)).getPrimaryPrincipal();
        ResponseResult responseResult = examinerService.updateSelfPassword(newPwd, examiner.getExaminerId());
        return responseResult;
    }

    @ResponseBody
    @RequestMapping("/findExaminerPwd")
    public ResponseResult findExaminerPwd(String examinerName, String idNumber, String email){
        System.out.println("userName = " + examinerName + ", userIdentity = " + idNumber + ", email = " + email);
        ResponseResult responseResult=examinerService.findPwd(examinerName, idNumber, email);
        return responseResult;
    }

    @ResponseBody
    @RequestMapping("/getExaminers")
    public DataPage getExaminerPerms(){
        Session session = SecurityUtils.getSubject().getSession();
        //获取‘操作者’信息
        Examiner examiner = (Examiner) ((PrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)).getPrimaryPrincipal();
        DataPage dataPage=examinerService.getExaminers(examiner);
        System.out.println(dataPage);
        return dataPage;
    }

    @ResponseBody
    @RequestMapping("/getExaminerInfo")
    public Map<String, Object> getExaminerInfo(){
        Session session = SecurityUtils.getSubject().getSession();
        //获取‘操作者’信息
        Examiner examiner = (Examiner) ((PrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)).getPrimaryPrincipal();
        Map<String, Object> map=roleService.getExaminerInfo(examiner);

        return map;
    }


}